import { defineEventHandler, readBody, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import { requireUser } from '../../utils/auth.js';

export default defineEventHandler(async (event) => {
  try {
    const { userId } = requireUser(event);

    const { noteId, newName } = await readBody(event);

    const db = await getDbConnection();
    await db.run(
      `UPDATE notes 
       SET name = ?, updated_at = CURRENT_TIMESTAMP 
       WHERE id = ? 
         AND user_id = ?`,
      [newName, noteId, userId]
    );

    return { success: true };
  } catch (error) {
    console.error('Error renaming note:', error);
    if (error && error.statusCode) throw error;
    throw createError({ statusCode: 500, statusMessage: 'Failed to rename note' });
  }
});
